package com.seabook.happy.website.daos;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.seabook.happy.website.pojos.Mood;
import com.seabook.happy.website.pojos.News;

public class NewsDao {
	private DatastoreService datastore = DatastoreServiceFactory
	.getDatastoreService();
	
	public boolean insertNews(News news) {
		Entity newsEntity = new Entity(EntitesKind.NEWS_KIND);

		newsEntity.setProperty("newsContent", news.getNewsContent());
		newsEntity.setProperty("modifiedDate", new Date());

		datastore.put(newsEntity);
		return true;
	}
	
	public boolean deleteNews(String key) {
		datastore.delete(KeyFactory.stringToKey(key));
		return true;
	}
	
	public boolean updateNews(String key, Text newsContent) {
		Entity newsEntity = null;
		try {
			newsEntity = datastore.get(KeyFactory.stringToKey(key));
		} catch (EntityNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		
		newsEntity.setProperty("newsContent", newsContent);
		newsEntity.setProperty("modifiedDate", new Date());
		
		datastore.put(newsEntity);
		return true;
	}
	
	public List<News> listLatestNews(int number) {
		Query query = new Query(EntitesKind.NEWS_KIND);
		query.addSort("modifiedDate", Query.SortDirection.DESCENDING);
		List<Entity> newsEntities = datastore.prepare(query).asList(
				FetchOptions.Builder.withLimit(number));
		return transferEntity2News(newsEntities);
	}

	private List<News> transferEntity2News(List<Entity> newsEntities) {
		List<News> newsList = new ArrayList<News>();
		for (Entity entity : newsEntities) {
			News news = new News();
			news.setKey(entity.getKey());
			news.setNewsContent((Text)entity.getProperty("newsContent"));
			news.setModifiedDate((Date)entity.getProperty("modifiedDate"));
			newsList.add(news);
		}
		return newsList;
	}
	
	public List<News> listAllNews() {
		Query query = new Query(EntitesKind.NEWS_KIND);
		query.addSort("modifiedDate", Query.SortDirection.DESCENDING);
		List<Entity> newsEntities = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
		return transferEntity2News(newsEntities);
	}
}
